//
//  HEIMTWChatViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/24.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEIMTWChatViewController.h"
#import "HEIMTextCell.h"
#import "HEIMInfoEntity.h"
#import "HEIMForward.h"
#import "HEActivityHeader.h"
#import "HEIMImageViewCell.h"
#import "HEIMAudioCell.h"
#import "HEMediaManager.h"
#import "HETWChatManage.h"
#import "HEIMConsulReportCell.h"
#import "HEDocImMsgModel.h"
#import "HEIMTWFormCell.h"
#import "HEIMVideoCell.h"
#import "HEOrderViewController.h"
#import "HEConsulCommentViewController.h"
#import "HETWOpraetionView.h"
#import "HETimerWeakTarget.h"
#import "HEChatBar.h"

@interface HEIMTWChatViewController ()<UITableViewDelegate, UITableViewDataSource, HEIMMessageCellDelegate, HESocketManagerDelegate, HEChatBarDelegate, HETWChatManageDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray <HEIMMessageModel *>*dataSource;

@property (nonatomic, strong) GDFormModel *formModel;
//@property (nonatomic, strong) HEOldPelOrgModel *details;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) HEIMForward *imDataForward;
@property(nonatomic, assign) BOOL fristInto;


@property (nonatomic, strong) HEChatBar *chatBar;


@property (nonatomic,assign) NSInteger second;
@property (nonatomic,assign) NSInteger minute;
@property (nonatomic,assign) NSInteger hour;
@property (nonatomic, strong) NSTimer *timer;


@property (strong, nonatomic) UILabel *hourLabel;
@property (strong, nonatomic) UILabel *minuteLabel;
@property (strong, nonatomic) UILabel *secondLabel;
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) YYLabel *consulLb;
@property (strong, nonatomic) QMUIButton *stateView;

@property (nonatomic, assign) NSInteger totalConsulCnt;
@property (nonatomic, assign) NSInteger specificCnt;

@property (nonatomic, strong) HEDocImMsgModel *detailModel;

// 底部操作视图
@property (nonatomic, strong) HETWOpraetionView *whetherEndView; // 询问是否结束问诊
@property (nonatomic, strong) HETWOpraetionView *endView; // 已结束
@property (nonatomic, strong) HETWOpraetionView *refuseView; // 已拒绝
@property (nonatomic, strong) UIView *exprieView;


/*!
 * 发送消息时，会置YES
 * 输入框高度变更，比如输入文字换行、切换到 More、Face 页面、键盘弹出、键盘收缩
 */
@property (nonatomic, assign) BOOL allowScrollToBottom;

@property(nonatomic, assign) BOOL needBackRefresh;

@property (nonatomic, strong) HEIMSession *session; /// 当前会话

@end

@implementation HEIMTWChatViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.chatBar close];
    if (self.needBackRefresh && self.backBlock) {
        self.backBlock();
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[HESocketManager sharedManager] removeDelegate:self];
    [HETWChatManage sharedManager].delegate = nil;
    
    [[HEMediaManager sharedManager] stopPlay];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] isEnabled];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    
    [[HESocketManager sharedManager] addDelegate:self];
    [HETWChatManage sharedManager].delegate = self;
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.chatBar open];
}


- (void)dealloc {
    DLog(@"HEIMTWChatViewController dealloc");
    [self stopTime];
//    [[HEIMKit sharedKit] removeAllUserInfos];
}

- (void)initSession {
    _session = [HEIMSession session:_docId type: HEIMSessionTypeP2P];
    _session.referenceId = _inst_id;
    [[HEIMConversationManager sharedManager] registeSession: _session];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = CViewBgColor;
    
    HEIMKitInfo *docInfo = [[HEIMKit sharedKit] infoByUser:_docId];
    self.title = docInfo.showName;
    
    [self initSession];
    
    _pageNum = 1;
    _pageSize = 9999;
    _fristInto = YES;
    _totalConsulCnt = 0;

    [self.view addSubview:self.tableView];
    
    [self initCell];
    
    [self setupCahceData];
    
    /**
        加载问诊记录列表  ---》 获取问诊状态、计算问诊次数  ---> 获取问诊过期时间
     */
    [self loadData];
}
  
- (void)startTime {
    [self.timer fire];
}

- (void)stopTime {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}
 
- (void)timeHeadle {
    if (self.second <= 0 && self.minute <= 0 && self.hour <= 0) {
        _hourLabel.text = [NSString stringWithFormat:@"%.2ld", _hour];
        _minuteLabel.text = [NSString stringWithFormat:@"%.2ld", _minute];
        _secondLabel.text = [NSString stringWithFormat:@"%.2ld", _second];
        [self stopTime];
        
        [self hideInputView];
        
        [self finishTW];

        [WOAlert alertShowTitle:@"温馨提示" message:@"您该次图文问诊时间已结束~" cancelButtonTitle:@"确定" otherButtonTitles:nil block:^(NSInteger buttonIndex) {
        }];
        return;
    }
    
    self.second--;
    if (self.second==-1) {
        self.second=59;
        self.minute--;
        if (self.minute==-1) {
            self.minute=59;
            self.hour--;
        }
    }
    
    _hourLabel.text = [NSString stringWithFormat:@"%.2ld", _hour];
    _minuteLabel.text = [NSString stringWithFormat:@"%.2ld", _minute];
    _secondLabel.text = [NSString stringWithFormat:@"%.2ld", _second];
    
    if (self.second <= 0 && self.minute <= 0 && self.hour <= 0) {
        [self stopTime];
        
        [self hideInputView];

        [self finishTW];
        
        [WOAlert alertShowTitle:@"温馨提示" message:@"您该次图文问诊时间已结束~" cancelButtonTitle:@"确定" otherButtonTitles:nil block:^(NSInteger buttonIndex) {
        }];
    }
}

- (void)setupCahceData {
    
    HEDocImMsgModel *doc = [HEDocImMsgModel new];
    doc.doc_id = _docId;
    doc.doc_name = _docName;
    doc.inst_id = _inst_id;
    [HETWChatManage sharedManager].orgData = doc;
    
    [self.dataSource addObjectsFromArray: [[HETWChatManage sharedManager] getIMCacheWithSession: _session]];
    [[HETWChatManage sharedManager] sendQueueIMMassage];
}

- (void)configSessionUserInfo {
}

 
#pragma mark - 图文问诊剩余次数
- (void)loadConsulCntData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_inst_id forKey:@"inst_id"];
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:Kproduct_send_cnt parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        self.totalConsulCnt = [response.data integerValue];
        
        if (response.success) {
            [self configView];
            [self dealConsulCntData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

/// 计算用户图文问诊剩余次数
- (void)dealConsulCntData {
    NSInteger userCnt = 0;
    
    for (HEIMMessageModel *model in self.dataSource) {
        if (model.isOwn) {
            userCnt += 1;
        }
    }
    self.specificCnt = self.totalConsulCnt - userCnt + 1; // +1 是为了排除最开始的表单信息
    
    NSString *cnt = [NSString stringWithFormat:@"%ld", _specificCnt];
    NSString *desc = [NSString stringWithFormat:@"咨询时间结束前还可以向医生发送消息%@次", cnt];

    NSDictionary *attributes = @{NSFontAttributeName: DYFont(16), NSForegroundColorAttributeName: CNavDargGrayColor};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:desc attributes:attributes];
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:cnt] color:CPriceColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
    }];
 
    _consulLb.attributedText = text;
    
    if (self.specificCnt <= 0) {
        [self hideInputView];

        [WOAlert alertShowTitle:@"温馨提示" message:@"您可发送消息次数已用完，请耐心等待医生回复~" cancelButtonTitle:@"确定" otherButtonTitles:nil block:^(NSInteger buttonIndex) {
        }];
    }
}

- (void)initInputView {
    if (!_isExprie) {
        [self.view addSubview:self.chatBar];
        [self.chatBar open];
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(ZXNavBarHeight);
            make.left.and.width.equalTo(self.view);
            make.bottom.equalTo(self.chatBar.mas_top);
        }];
        [self.chatBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.view);
            make.height.mas_greaterThanOrEqualTo(@(kLCCKChatBarMinHeight));
            make.bottom.equalTo(self.view);
        }];
    }else {
        self.tableView.frame = CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight);
    }
}

- (void)initCell {
    
    _sections = @[].mutableCopy;
    _dataSource = @[].mutableCopy;
    
    NSMutableArray *classArr = [NSMutableArray array];
    
    //
    GDFiterCellModel *textModel = [GDFiterCellModel new];
    textModel.cellKlass = HEIMTextCell.class;
    
    GDFiterCellModel *imageModel = [GDFiterCellModel new];
    imageModel.cellKlass = HEIMImageViewCell.class;
    
    GDFiterCellModel *audioModel = [GDFiterCellModel new];
    audioModel.cellKlass = HEIMAudioCell.class;
    
    GDFiterCellModel *reportCellModel = [GDFiterCellModel new];
    reportCellModel.cellKlass = HEIMConsulReportCell.class;
    
    GDFiterCellModel *twFormCellModel = [GDFiterCellModel new];
    twFormCellModel.cellKlass = HEIMTWFormCell.class;
    
    GDFiterCellModel *videoCellModel = [GDFiterCellModel new];
    videoCellModel.cellKlass = HEIMVideoCell.class;
    
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[textModel, imageModel, audioModel, reportCellModel, twFormCellModel, videoCellModel].mutableCopy;
    
    for (GDFiterCellModel *model in classArr) {
        NSString *cellIdOwner = [NSString stringWithFormat:@"%@_%@_%@",NSStringFromClass(model.cellKlass), HECellIdentifierOwnerSelf, HECellIdentifierSingle];
        NSString *cellIdOwnerOther = [NSString stringWithFormat:@"%@_%@_%@",NSStringFromClass(model.cellKlass), HECellIdentifierOwnerOther, HECellIdentifierSingle];
        [self.tableView registerClass:model.cellKlass forCellReuseIdentifier: cellIdOwner];
        [self.tableView registerClass:model.cellKlass forCellReuseIdentifier: cellIdOwnerOther];
    }
}

- (void)loadData {
   HEPageRequest *req = [HEPageRequest new];
   req.pageNum = _pageNum;
   req.pageSize = _pageSize;
//    req.sort = @"desc";
   [req addParmas: _inst_id key:@"inst_id"];

   [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KgetDocResponse parameters:req success:^(id  _Nonnull responseObject) {
       NSLog(@"response：  %@", [responseObject mj_JSONString]);
       HEPageResponse *response = [HEPageResponse mj_objectWithKeyValues:responseObject];
       if (response.success) {
           NSArray <HEDocImMsgModel *> *msgList = [HEDocImMsgModel mj_objectArrayWithKeyValuesArray: response.data.list];
           NSArray <HEIMMessageModel *> *endMsgs = [HEIMForward transformTWModel:msgList];
           
           if (msgList.count > 0) {
               self.pageNum += 1;
               self.detailModel = msgList.firstObject;
               [self loadConsulCntData];
           }
           [self.tableView.mj_header endRefreshing];
           
           if (self.fristInto) {
               NSRange range = NSMakeRange(0, endMsgs.count);
               NSIndexSet *nsindex = [NSIndexSet indexSetWithIndexesInRange:range];
               [self.dataSource insertObjects:endMsgs atIndexes:nsindex];
               [self.tableView reloadData];
               [self scrollToBottom];
           }else {
               dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
                   NSMutableArray *messages = [NSMutableArray arrayWithArray: endMsgs];
                   [messages addObjectsFromArray:self.dataSource];
                   NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:endMsgs.count];
                   [endMsgs enumerateObjectsUsingBlock:^(id message, NSUInteger idx, BOOL *stop) {
                       NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                       [indexPaths addObject:indexPath];
                   }];
                   dispatch_async(dispatch_get_main_queue(),^{
                       CGSize beforeContentSize = self.tableView.contentSize;
                       BOOL animationEnabled = [UIView areAnimationsEnabled];
                       if (animationEnabled) {
                           [UIView setAnimationsEnabled:NO];
                           [self.tableView beginUpdates];
                           self.dataSource = [messages mutableCopy];
                           [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
                           [self.tableView reloadData];
                           [self.tableView endUpdates];
                           CGSize afterContentSize = self.tableView.contentSize;
                           CGPoint afterContentOffset = self.tableView.contentOffset;
                           CGPoint newContentOffset = CGPointMake(afterContentOffset.x, afterContentOffset.y + afterContentSize.height - beforeContentSize.height);
                           [self.tableView setContentOffset:newContentOffset animated:NO] ;
                           [UIView setAnimationsEnabled:YES];
                       }
                   });
               });
           }
       }
   } failure:^(NSError * _Nonnull error) {
       [self.tableView.mj_header endRefreshing];
   }];
}

- (void)getExprieDate {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_inst_id forKey:@"inst_id"];
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KgetUserAsk parameters:dict success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        NSArray <HEDocImMsgModel *> *msgList = [HEDocImMsgModel mj_objectArrayWithKeyValuesArray: response.data];
        
        HEDocImMsgModel *model = msgList.firstObject;
        NSDate *exprie = [NSDate timestringToDate: model.expiration_date];
        NSDate *nowDate = [NSDate date];
        
        NSTimeInterval nowTime = nowDate.timeIntervalSinceNow;
        NSTimeInterval endTime = exprie.timeIntervalSinceNow;

        NSInteger aaa = endTime - nowTime;
        
        self.hour = aaa/3600;
        self.minute = (aaa%3600)/60;
        self.second = aaa%60;
   
        [self startTime];
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)finishTW {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_inst_id forKey:@"inst_id"];
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KtwFinish parameters:dict success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        
        if (response.success) {
            [self hideInputView];
            [self.tableView setContentInset:UIEdgeInsetsMake(0,0,0,0)];
            self.zx_navRightBtn.hidden = YES;
            self.exprieView.hidden = YES;
            
            [self.view addSubview:self.endView];
            [self scrollToBottom];
            
            self.needBackRefresh = YES;
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark - 图文问诊过期时间 / 结束
- (void)configView {
    if (self.detailModel.status == 0) { // 未开始
//        [self setNav];
        [self.view addSubview: self.exprieView];
        [self initInputView];
    }
    else if(self.detailModel.status == 1) { // 进行中
        [self setNav];
        [self.view addSubview: self.exprieView];
        [self initInputView];
        [self getExprieDate];
    }
    else if(self.detailModel.status == 2) { // 已结束
        [self.view addSubview:self.endView];
    }
    else if(self.detailModel.status == 3) { // 被医生拒绝，可进行退款
        [self.view addSubview:self.refuseView];
    }
    else {
        [self.view addSubview:self.endView];
    }
    
    [self scrollToBottom];
}

- (void)setNav {
    // 设置导航栏按钮
    KWeakSelf
    [self zx_setRightBtnWithText:@"结束问诊" clickedBlock:^(UIButton * _Nonnull btn) {
        [weakSelf.chatBar endInputing];
        weakSelf.whetherEndView.hidden = NO;
        [weakSelf.view addSubview:weakSelf.whetherEndView];
        [weakSelf.view bringSubviewToFront:weakSelf.whetherEndView];
    }];
    self.zx_navRightBtn.zx_tintColor = CNavBgColor;
}

- (HETWOpraetionView *)whetherEndView {
    if (!_whetherEndView) {
        CGFloat endViewHeight = 160;
        _whetherEndView = [[HETWOpraetionView alloc] initWithFrame:CGRectMake(0, kScreenHeight - endViewHeight, KScreenWidth, endViewHeight) withType:HETWOpraetionTypeWhetherEnd];
        KWeakSelf
        [_whetherEndView operationActionHandler:^(HETWOpraetionType type, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                weakSelf.whetherEndView.hidden = YES;
            }else { // 结束
                weakSelf.whetherEndView.hidden = YES;
                [self finishTW];
            }
        }];
    }
    return _whetherEndView;
}

- (void)hideInputView {
    [self.chatBar endInputing];

    [self.chatBar mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.height.offset(0);
        make.bottom.equalTo(self.view).offset(-ZXSafeAreaBottom);
    }];
    
    self.chatBar.hidden = YES;
}

// 医生拒绝
- (HETWOpraetionView *)refuseView {
    if (!_refuseView) {
        CGFloat endViewhHeight = 120;
        self.tableView.frame = CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight - endViewhHeight);
     
        HETWOpraetionView *refuseView = [[HETWOpraetionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_tableView.frame), KScreenWidth, endViewhHeight) withType:HETWOpraetionTypeDocRefuse];
        [self.view addSubview:refuseView];
        
        [refuseView operationActionHandler:^(HETWOpraetionType type, NSInteger buttonIndex) {
            HEOrderViewController *vc = [HEOrderViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }];
        _refuseView = refuseView;
    }
    return _refuseView;
}

// 过期或者结束的底部视图
- (HETWOpraetionView *)endView {
    if (!_endView) {
        HEIMKitInfo *docInfo = [[HEIMKit sharedKit] infoByUser:_docId];

        CGFloat endViewhHeight = 160;
        self.tableView.frame = CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight - endViewhHeight);
        
        HETWOpraetionView *endView = [[HETWOpraetionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_tableView.frame), KScreenWidth, endViewhHeight) withType:HETWOpraetionTypeEnd];
        [self.view addSubview:endView];
        
        KWeakSelf
        [endView operationActionHandler:^(HETWOpraetionType type, NSInteger buttonIndex) {
            HEConsulCommentViewController *vc = [HEConsulCommentViewController new];
            vc.target_id = weakSelf.docId;
            vc.type = HEConsulCommentTypeTW;
            vc.out_inst_id = weakSelf.inst_id;
            vc.avatar = docInfo.avatarUrlString;
            vc.doc_name = docInfo.showName;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        _endView = endView;
    }
    return _endView;
}
  
#pragma mark -

- (void)scrollToBottom
{
    [self.tableView layoutIfNeeded];
    CGFloat yOffset = 0; //设置要滚动的位置 0最顶部 CGFLOAT_MAX最底部
    if (self.tableView.contentSize.height > self.tableView.bounds.size.height) {
        yOffset = self.tableView.contentSize.height - self.tableView.bounds.size.height;
    }
    [self.tableView setContentOffset:CGPointMake(0, yOffset) animated: !self.fristInto];
    
    self.fristInto = NO;
}

#pragma mark - UITableViewDataSource
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    HEIMMessageModel *imModel = self.dataSource[indexPath.row];

    HEIMMessageCell *cell = [_tableView dequeueReusableCellWithIdentifier: imModel.cellIdentifier];
    cell.delegate = self;
    [cell configCellWithModel: imModel]; 
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HEIMMessageModel *imModel = self.dataSource[indexPath.row];

 
  return [tableView fd_heightForCellWithIdentifier: imModel.cellIdentifier cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
      [cell configCellWithModel: imModel];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.chatBar endInputing];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.chatBar endInputing];
}

#pragma mark - HEChatBarDelegate
- (void)chatBarFrameDidChange:(HEChatBar *)chatBar shouldScrollToBottom:(BOOL)shouldScrollToBottom {
    [UIView animateWithDuration:LCCKAnimateDuration animations:^{
        [self.tableView.superview layoutIfNeeded];
        self.allowScrollToBottom = shouldScrollToBottom;
        [self scrollToBottomAnimated:NO];
        
//        [self scrollToBottom];

    } completion:nil];
}

- (void)scrollToBottomAnimated:(BOOL)animated {
    if (!self.allowScrollToBottom) {
        return;
    }
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if (rows > 0) {
        dispatch_block_t scrollBottomBlock = ^ {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
                                  atScrollPosition:UITableViewScrollPositionBottom
                                          animated:animated];
        };
        if (animated) {
            //when use `estimatedRowHeight` and `scrollToRowAtIndexPath` at the same time, there are some issue.
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                scrollBottomBlock();
            });
        } else {
            scrollBottomBlock();
        }
        
    }
}

- (void)sendMessage:(HEIMMessageModel *)message {
    
    if (self.specificCnt == 0) {
        return;
    }

    [self.dataSource addObject:message];

    dispatch_async(dispatch_get_main_queue(), ^{
 
        [self.tableView reloadData];
        
        // 计算剩余次数
        [self dealConsulCntData];
        
        [self scrollToBottom];

    });
    [[HETWChatManage sharedManager] sendMessage:message];
}

#pragma mark - HETWChatManageDelegate
- (void)sendMessageHandler:(HEIMMessageModel *)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
    
    self.needBackRefresh = YES;
}

#pragma mark - HESocketManagerDelegate
- (void)onRecvMessages:(HEIMMessageModel *)message {
    if (![message.message.refrenceId isEqualToString:_inst_id]) {
        return;
    }
    [self.dataSource addObject:message];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self scrollToBottom];
    });
    
    if (!message.message.isOwn) {
        if (!_timer) { // 医生第一次回复时，开始刷新过期时间。
            [self getExprieDate];
        }
    }
}

- (void)loginSuccessHandler {
    DLog(@"重新登录成功")
    [[HETWChatManage sharedManager] sendQueueIMMassage];
}

#pragma mark - HEIMMessageCellDelegate
- (void)onTapMessage:(HEIMMessage *)message {
    if (message.type == HEIMMessageTypeAudio) {
        [[HEMediaManager sharedManager] playByMessage: message];
    }else if (message.type == HEIMMessageTypeConsulReport) {
 
    }
}

#pragma mark - UITableViewDelegate
#pragma lazy load

- (HEIMForward *)imDataForward {
    if (!_imDataForward) {
        _imDataForward = [HEIMForward new];
    }
    return _imDataForward;
}

- (NSMutableArray<HEIMMessageModel *> *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] init];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
            [UITableView appearance].sectionHeaderTopPadding = 0;
        } else {
            // Fallback on earlier versions
        }

        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        
        HEActivityHeader *header = [HEActivityHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _tableView.mj_header = header;
        
    }
    return _tableView;
}


#pragma mark - lazy data
- (UIView *)exprieView {
    if (!_exprieView) {
        
        UIView *warp = [[UIView alloc] initWithFrame:CGRectMake(15, ZXNavBarHeight + 10, KScreenWidth - 30, 100)];
        warp.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
        warp.layer.shadowColor = [UIColor colorWithRed:13/255.0 green:98/255.0 blue:218/255.0 alpha:0.08].CGColor;
        warp.layer.shadowOffset = CGSizeMake(0,5);
        warp.layer.shadowOpacity = 1;
        warp.layer.shadowRadius = 12; 
        [self.view addSubview:warp];
        _exprieView = warp;
        
        // 姓名
        QMUIButton *stateView = [[QMUIButton alloc] init];
        stateView.imagePosition = QMUIButtonImagePositionLeft;// 将图片位置改为在文字下方
        stateView.tintColorAdjustsTitleAndImage = CNavLightBlackColor;
        stateView.adjustsImageTintColorAutomatically = NO;
        stateView.spacingBetweenImageAndTitle = 5;
        [stateView setImage:IMAGE_NAMED(@"zixun") forState:UIControlStateNormal];
        [stateView setTitle: @"咨询中" forState:UIControlStateNormal];
        stateView.titleLabel.font = DYBlodFont(16);
        [warp addSubview:stateView];
        _stateView = stateView;
        
        [stateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(warp).offset(15);
            make.left.equalTo(warp).offset(15);
        }];
         
        [self.tableView setContentInset:UIEdgeInsetsMake(110,0,0,0)];
        
        
        YYLabel *consulLb = [YYLabel new];
        consulLb.textAlignment = NSTextAlignmentCenter;
        consulLb.textColor = CNavBgColor;
        consulLb.numberOfLines = 0;
        [warp addSubview: consulLb];
        _consulLb = consulLb;
        
        [consulLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(stateView.mas_bottom).offset(10);
            make.bottom.equalTo(warp.mas_bottom).offset(-15);
            make.left.equalTo(warp).offset(15);
            make.right.equalTo(warp).offset(-10);
        }];
        
        NSDictionary *attributes = @{NSFontAttributeName: DYFont(16), NSForegroundColorAttributeName: CNavDargGrayColor};
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"咨询时间结束前还可以向医生发送消息0次" attributes:attributes];
        //设置高亮色和点击事件
        [text yy_setTextHighlightRange:[[text string] rangeOfString:@"0"] color:CPriceColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        }];
     
        consulLb.attributedText = text;
        
        
        CGFloat label_width = 30;
        CGFloat label_Height = 30;

        self.contentView = [UIView new];
    //    self.contentView.backgroundColor = [UIColor magentaColor];
        [warp addSubview:self.contentView];
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(4*label_width, label_Height));
            make.right.equalTo(warp).offset(-10);
            make.centerY.equalTo(stateView);
        }];
     
        self.hourLabel = [UILabel new];
        self.hourLabel.text = @"--";
        self.hourLabel.textAlignment = NSTextAlignmentCenter;
        self.hourLabel.font = [UIFont systemFontOfSize:15];
        self.hourLabel.backgroundColor = KHexColor(@"EBF3FE");
        self.hourLabel.layer.cornerRadius = 6;
        self.hourLabel.layer.masksToBounds = YES;
        self.hourLabel.textColor = CNavBgColor;
        [self.contentView addSubview:self.hourLabel];
         
        self.minuteLabel = [UILabel new];
        self.minuteLabel.text = @"--";
        self.minuteLabel.textAlignment = NSTextAlignmentCenter;
        self.minuteLabel.font = [UIFont systemFontOfSize:15];
        self.minuteLabel.backgroundColor = KHexColor(@"EBF3FE");
        self.minuteLabel.layer.cornerRadius = 6;
        self.minuteLabel.layer.masksToBounds = YES;
        self.minuteLabel.textColor = CNavBgColor;
        [self.contentView addSubview:self.minuteLabel];
        
        self.secondLabel = [UILabel new];
        self.secondLabel.text = @"--";
        self.secondLabel.textAlignment = NSTextAlignmentCenter;
        self.secondLabel.font = [UIFont systemFontOfSize:15];
        self.secondLabel.backgroundColor = KHexColor(@"EBF3FE");
        self.secondLabel.layer.cornerRadius = 6;
        self.secondLabel.layer.masksToBounds = YES;
        self.secondLabel.textColor = CNavBgColor;
        [self.contentView addSubview:self.secondLabel];
        
        UILabel *speciLb = [UILabel new];
        speciLb.text = @"剩余";
        speciLb.textAlignment = NSTextAlignmentCenter;
        speciLb.font = DYFont(15);
        speciLb.textColor = CNavBgColor;
        [self.contentView addSubview: speciLb];
        
        UILabel *spLb1 = [UILabel new];
        spLb1.text = @":";
        spLb1.textAlignment = NSTextAlignmentCenter;
        spLb1.font = [UIFont systemFontOfSize:15];
        spLb1.textColor = CNavBgColor;
        [self.contentView addSubview: spLb1];
        
        UILabel *spLb2 = [UILabel new];
        spLb2.text = @":";
        spLb2.textAlignment = NSTextAlignmentCenter;
        spLb2.font = [UIFont systemFontOfSize:15];
        spLb2.textColor = CNavBgColor;
        [self.contentView addSubview: spLb2];
        
        [speciLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contentView);
            make.right.equalTo(self.hourLabel.mas_left).offset(-5);
            make.height.equalTo(self.contentView.mas_height);
        }];
            
        [spLb1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contentView);
            make.left.equalTo(self.hourLabel.mas_right);
            make.width.offset(15);
            make.height.equalTo(self.contentView.mas_height);
        }];
        
        [spLb2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contentView);
            make.left.equalTo(self.minuteLabel.mas_right);
            make.width.offset(15);
            make.height.equalTo(self.contentView.mas_height);
        }];
        
        
        NSArray *arr = @[self.hourLabel,self.minuteLabel,self.secondLabel];

        [arr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView);
            make.bottom.equalTo(self.contentView);
        }];
        
        [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:30 leadSpacing:0 tailSpacing:0];
    }
    return _exprieView;
}

#pragma mark - getter

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [HETimerWeakTarget scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeHeadle) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (HEChatBar *)chatBar {
    if (!_chatBar) {
        _chatBar = [[HEChatBar alloc] initWithFrame:CGRectZero type:HEIMUserModelTypeConsul];
        _chatBar.delegate = self;
        _chatBar.session = _session;
        [self.view addSubview: _chatBar];
        [self.view bringSubviewToFront:_chatBar];
    }
    return _chatBar;
}

@end
